package com.i2863.receipt.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


@Controller
@RequestMapping(value = "/file",produces = "text/html;charset=UTF-8")
public class UploadFileUtil {

//	@Value("${web.upload-path}")
//	private String path = "D:/appConfig/upload/img/";

    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file){
        JSONObject json = new JSONObject();

        if(file.isEmpty()){
            json.put("code", 1);
            json.put("msg", "文件为空");
            return json.toJSONString();
        }

        String fileName = file.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf(".")+1);
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+suffix;
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);


        //图片上传七牛
        try {
            String uploadToken = Auth.create(QiNiuUtil.ak, QiNiuUtil.sk).uploadToken(QiNiuUtil.bucket);//生成上传token
            UploadManager uploadManager = QiNiuUtil.getUploadManager();
            Response res = uploadManager.put(file.getBytes(), newFileName, uploadToken);
            String body = res.bodyString();
            JSONObject object = JSON.parseObject(body);
            String imgPath = QiNiuUtil.baseURL+object.getString("key");
            json.put("code", 0);
            json.put("msg", "上传成功");
            json.put("path", imgPath);
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
            json.put("code", 1);
            json.put("msg", "上传出错");
        }
        return json.toJSONString();

    }


}

